package cetcbigdata.da.personal_service.gansu;

import cetcbigdata.da.base.Base;
import cetcbigdata.da.base.DownloadAndUploadMinio;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.alibaba.datax.common.plugin.RecordSender;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.seimicrawler.xpath.exception.XpathSyntaxErrorException;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GSpersonUtil extends Base {
    @Override
    public void getData(RecordSender recordSender, List<Object> fieldsList) {

    }

    @Override
    public JSONObject getDataDemo() {
        return null;
    }

    //开头信息
    public static JSONObject getTitle(String response) {
        JSONObject result = new JSONObject();

        JXDocument jxDocument = new JXDocument(response);
        List<Object> conTitle = jxDocument.sel("//div[@class=\"con-Title\"]");
        for (Object o : conTitle){
            String[] array = ((Element)o).text().split(" ");
            result.put("名称", array[0]);
            result.put("位置", array[1]);
        }
        List<Object> lis = jxDocument.sel("//ul[@class='con-Ticks']/li");
        for (Object o : lis){
            Element li = (Element) o;
            for (int i = 0 ; i < li.children().size(); i+=2){
                String key = li.child(i+1).text();
                String value = li.child(i).text();
                result.put(key,value);
            }
        }
        List<Object> trs = jxDocument.sel("//div[@class='detail_table fl']/table/tbody/tr");
        for (Object trObj : trs) {
            Element tr =  (Element) (trObj);
            Elements tds = tr.children();
            for (int i = 0, len = tds.size(); i < len; i+=2 ) {
                String key = tds.get(i).text();
                String value = tds.get(i+1).text();
                result.put(key, value);
            }
        }
        return result;
    }

    //基本信息
    public static JSONObject getBaseinfo(String response) {
        JSONObject result = new JSONObject();
        result.put("开头信息", getTitle(response));
        JXDocument jxDocument = new JXDocument(response);
        try {
            List<Object> middle = jxDocument.sel("//tr[@valign=\"middle\"]//td[@width=\"130\"]");
            for (Object o : middle) {
                String key = ((Element) o).text();
                String value = ((Element) o).nextElementSibling().text();
                result.put(key, value);
            }
        }catch (Exception e){
            return null;
        }
        return result;
    }

    //受理条件
    public static String getAcceptcondition(String response) {
        JXDocument jxDocument = new JXDocument(response);
        try {
            List<Object> list = jxDocument.sel("//div[@class=\"matters-faq-answer\"]");
            for (Object o : list){
                return ((Element) o).text();
            }
        } catch (XpathSyntaxErrorException e) {
            return null;
        }
        return "";
    }

    //申报材料
    public static JSONArray getMaterials(String response, String taskCode, String taskHandleItem) {
        JSONArray results = new JSONArray();
        try {
            Pattern pattern = Pattern.compile("showQuestion\\('(\\S*)','(\\S*)'\\);");
            Matcher matcher = pattern.matcher(response);
            while (matcher.find()){
                String url = "https://zwfw.gansu.gov.cn/szgs/bszn/submit.do?" +
                        "rowGuid="+ matcher.group(1) +
                        "&taskType="+ matcher.group(2) +
                        "&materialids=" +
                        "&flag=false";
                JSONObject header = new JSONObject();
                header.put("Referer", "https://zwfw.gansu.gov.cn/szgs/bszn/index.do?taskCode="+taskCode+"&taskHandleItem="+taskHandleItem);
                header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)");
                String content = getReq(url,header,new JSONObject());
                String matrialHtml = JSONObject.parseObject(content).getJSONObject("params").getString("matrialHtml");
                JXDocument jxDocument = new JXDocument(matrialHtml);
                List<Object> titleList = jxDocument.sel("//div[@class=\"prev lf\"]");
                String[] matrialNames = new String[0];
                for (Object o : titleList){
                    matrialNames = ((Element) o).getElementsByAttributeValue("class", "rf").text().split(" ");
                }
                List<Object> bodyList = jxDocument.sel("//div[@class=\"sbcl_tables_item\"]");
                int i = 0;
                for (Object o : bodyList){
                    JSONObject result = new JSONObject();

                    String[] array = ((Element) o).text().split(" ");
                    result.put("材料名称",matrialNames[i]);
                    result.put("来源渠道",array[0]);
                    result.put("材料类型",array[1]);
                    result.put("材料形式",array[2]);
                    result.put("纸质材料份数",array[3]);
                    result.put("材料必要性",array[4]);

                    if (((Element) o).getElementsByTag("a").size() > 0){
                        JSONObject matrialDownload = new JSONObject();
                        Elements a_onclics = ((Element) o).getElementsByTag("a");
                        ArrayList<String> id = new ArrayList<>();
                        for (Element element : a_onclics){
                            String a_onclic = element.attr("onclick");
                            Pattern filePat = Pattern.compile("downloadguid\\('(\\S*?)','");
                            Matcher fileMat = filePat.matcher(a_onclic);
                            while (fileMat.find()) {
                                id.add(fileMat.group(1));
                            }
                        }
                        //空白表格
                        try {
                            String emptyFileUrl;
                            String emptyFileMinioId;
                            JSONObject emptyFile = new JSONObject();
                            emptyFileUrl = "https://zwfw.gansu.gov.cn/attachfile/files/form/" + id.get(0);
                            emptyFileMinioId = fileDownloadAndUploadMinioGetImage(emptyFileUrl,
                                    id.get(0));
                            emptyFile.put("fileUrl", emptyFileUrl);
                            emptyFile.put("minioId", emptyFileMinioId);
                            matrialDownload.put("空白表格", emptyFile);
                        } catch (Exception e) {
                            matrialDownload.put("空白表格", "无");
                        }

                        try {
                            //示例详表
                            String sampleFileUrl;
                            String sampleFileMinioId;
                            JSONObject sampleFile = new JSONObject();
                            sampleFileUrl = "https://zwfw.gansu.gov.cn/attachfile/files/form/" + id.get(1);
                            sampleFileMinioId = fileDownloadAndUploadMinioGetImage(sampleFileUrl,
                                    id.get(1));
                            sampleFile.put("fileUrl", sampleFileUrl);
                            sampleFile.put("minioId", sampleFileMinioId);
                            matrialDownload.put("示例详表", sampleFile);
                        } catch (Exception e) {
                            matrialDownload.put("示例详表", "无");
                        }


                        result.put("材料下载",matrialDownload);
                    }else
                        result.put("材料下载","无");

                    result.put("纸质材料规格",array[6]);
                    result.put("填报须知",array[7]);
                    result.put("受理标准",array[8]);
                    result.put("要求提供材料的依据",array[9]);
                    results.add(result);
                    i++;
                }
            }
        } catch (Exception e) {
            return null;
        }
        return results;
    }

    //收费情况
    public static JSONObject getFeeinfo(String response) {
        JSONObject result = new JSONObject();
        JXDocument jxDocument = new JXDocument(response);
        try {
            List<Object> list = jxDocument.sel("//div[@class=\"sub2\"]//span");
            for (Object o : list){
                String key = ((Element) o).text();
                String value = ((Element) o).nextElementSibling().text();
                result.put(key, value);
            }
        } catch (XpathSyntaxErrorException e) {
            e.printStackTrace();
        }
        return result;
    }

    //法定依据
    public static String getBylaw(String response) {
        JXDocument jxDocument = new JXDocument(response);
        try {
            List<Object> list = jxDocument.sel("//p[@style=\"white-space: pre-line;\"]");
            for (Object o : list){
                return ((Element) o).text();
            }
        } catch (XpathSyntaxErrorException e) {
            return null;
        }
        return "";
    }

    //办理流程
    public static JSONObject getFlowinfo(String response, String taskCode, String taskHandleItem) {
        JSONObject result = new JSONObject();
        try {
            Pattern pattern = Pattern.compile("showActivity\\('(\\S*)'\\);");
            Matcher matcher = pattern.matcher(response);
            while (matcher.find()){
                String url = "https://zwfw.gansu.gov.cn/szgs/bszn/showActivity.do?rowGuid="+matcher.group(1);
                JSONObject header = new JSONObject();
                header.put("Referer", "https://zwfw.gansu.gov.cn/szgs/bszn/index.do?taskCode="+taskCode+"&taskHandleItem="+taskHandleItem);
                header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)");
                String strContent = getReq(url,header,new JSONObject());
                JSONObject content = JSONObject.parseObject(strContent);
                if (content.getString("code").equals("200")){

                    JSONArray ress = new JSONArray();

                    String activities = content.getJSONObject("params").getString("activities");
                    JSONArray flows = JSONArray.parseArray(activities);
                    for (Object o : flows){
                        JSONObject flow = (JSONObject) o;
                        JSONObject res = new JSONObject();
                        res.put("名称", flow.getString("activityName"));
                        res.put("办理结果", flow.getString("handleResult"));
                        res.put("审查标准", flow.getString("handleLinkExamine"));
                        ress.add(res);
                    }
                    result.put("流程详情", ress);
                }
            }
        } catch (Exception e) {
            result.put("流程详情", "无");
        }
        try {
            JSONObject flowFile = new JSONObject();
            Pattern pattern = Pattern.compile("var param = \"(\\S*)\";");
            Matcher matcher = pattern.matcher(response);
            while (matcher.find()){
                String fileUrl = null;
                String fileMinioId = null;
                try {
                    fileUrl = "https://zwfw.gansu.gov.cn/attachfile/files/handleflow/" + matcher.group(1);
                    fileMinioId = fileDownloadAndUploadMinioGetImage(fileUrl,
                            matcher.group(1));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                flowFile.put("url", fileUrl);
                flowFile.put("mininId", fileMinioId);
                result.put("办理流程图", flowFile);
            }
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    //常见问题
    public static Object getQuestion(String response, String taskCode, String taskHandleItem) {
        JSONObject result = new JSONObject();
        try {
            Pattern pattern = Pattern.compile("showQuestion\\('(\\S*)','(\\S*)'\\);");
            Matcher matcher = pattern.matcher(response);
            while (matcher.find()){
                String url = "https://zwfw.gansu.gov.cn/szgs/bszn/showQuestion.do?" +
                        "rowGuid="+ matcher.group(1) +
                        "&taskType="+ matcher.group(2);
                JSONObject header = new JSONObject();
                header.put("Referer", "https://zwfw.gansu.gov.cn/szgs/bszn/index.do?taskCode="+taskCode+"&taskHandleItem="+taskHandleItem);
                header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)");
                String strContent = getReq(url,header,new JSONObject());
                JSONObject content = JSONObject.parseObject(strContent);
                if (content.getString("code").equals("200")){
                    String questions = content.getJSONObject("params").getString("questions");
                    Pattern answerPat = Pattern.compile("\"answer\":\"(\\S*?)\"");
                    matcher = answerPat.matcher(questions);
                    while (matcher.find()){
                        result.put("答", matcher.group(1));
                    }
                    Pattern questionPat = Pattern.compile("\"question\":\"(\\S*?)\"");
                    matcher = questionPat.matcher(questions);
                    while (matcher.find()){
                        result.put("问", matcher.group(1));
                    }
                    return result;
                }
            }
        } catch (Exception e) {
            return "无常见问题";
        }
        return "无常见问题";
    }


    public static String fileDownloadAndUploadMinioGetImage(String url, String fileName ) throws Exception {
        JSONObject param = new JSONObject();
        JSONObject headers = new JSONObject();
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");

        //=========================================================测试性注释以下代码===============================================================
//        return DownloadAndUploadMinio.getInstance().downloadGet(
//                url,
//                headers,
//                param,
//                fileName
//        );
        return null;
    }
}
